import json

from django.core.cache import caches
from django.http import JsonResponse
from django.shortcuts import render

from dadashop import settings
from dadashop.settings import PIC_URL
from goods.models import SKU
from utils.baseview import BaseView

CARTS_CACHE = caches['carts_cache']
# Create your views here.
class CartView(BaseView):
    '''
        # 正常响应：
    {
        'code': 200,
        'data': skus_list,
        'base_url': PIC_URL
    }

    # 异常响应
    {
        "code":xxx,
        "error"：xxxx
    }
        '''
    def get(self, request, username):
        user=request.myuser
        skus_list= self.get_redis_carts_list_data(user)
        result={
            "code":200,
            "data":skus_list,
            "base_url":settings.PIC_URL
        }
        return JsonResponse(result)



    '''
    {
    'code': 200,
    'data':
    {
        'carts_count': count
    },
    'base_url': PIC_URL
}
    '''
    def post(self, request,username):
        data=json.loads(request.body)
        print(data)

        sku_id = data["sku_id"]
        count = int(data["count"])
        print(sku_id,count)
        sku = SKU.objects.get(id=sku_id)
        #检验上下架状态
        if not sku.is_launched:
            return JsonResponse({"code":400,"error":{"message":"this sku is not launched"}})
        #检验库存
        if int(sku.stock)<count:
            return JsonResponse({"code":400,"error":{"message":f"this sku is not enough,there are {SKU.stock} items left in stock."}})
        #先拿到用户购物车的数据
        user=request.myuser
        key=self.get_cache_key(user)
        carts_data=self.get_carts_count(key)
        #购物车为空
        if not carts_data:
            carts_data={sku_id:[count,1]}
        else:
            if sku_id in carts_data:
                #如果购物车有这个商品，则更新数量
                carts_data[sku_id][0]+=count
                if carts_data[sku_id][0]>sku.stock:
                    return JsonResponse({"code":400,"error":{"message":f"this sku is not enough,there are {SKU.stock} items left in stock."}})
            else:
                #如果购物车没有这个商品，则添加
                carts_data[sku_id]=[count,1]
        CARTS_CACHE.set(key,carts_data,timeout=None)
        print(carts_data,"存储成功")
        result={
            "code":200,
            "data":{
                "carts_count":len(carts_data)
            },
            "base_url":PIC_URL
        }
        '''
        "carts_userid":{sku_id1:[count,1],sku_id2:[count,1]}
        '''
        return JsonResponse(result)

    def merge_carts(self,offline_data,user):

        key=self.get_cache_key(user)
        online_data=self.get_carts_count(key)
        if not offline_data:
            return len(online_data)
        for skus in offline_data:
            sku_id=skus['id']
            count=int(skus['count'])
            if sku_id in online_data:
                online_data[sku_id][0]+=count
            else:
                online_data[sku_id]=[count, 1]
        CARTS_CACHE.set(key,online_data,timeout=None)
        print(online_data,"合并成功")

        return len(online_data)


    def get_cache_key(self,user):
        return "carts_%s"%user.id
    def get_carts_count(self,key):
        carts_count=CARTS_CACHE.get(key)
        if carts_count:
            return carts_count
        else:
            return {}
    def get_mysql_carts_list_data(self,sku_id,buy_num):
        skus_list=[]
        try:
            sku=SKU.objects.get(id=sku_id,is_launched=True)
        except Exception as e :
            return JsonResponse({
                "code": 400,
                "error": {
                    "message": e
                }
            })
        sku_sale_attr_name = []
        sku_sale_attr_val = []
        sale_attr_values = sku.sale_attr_value.all()
        for sale_attr_value in sale_attr_values:
            # 获取销售属性名称（从 SPUSaleAttr 获取）
            sku_sale_attr_name.append(sale_attr_value.spu_sale_attr.name)  # 添加属性名称（如 "尺寸", "颜色"）
            sku_sale_attr_val.append(sale_attr_value.name)  # 添加属性值（如 "18寸", "蓝色"）
        skus_list.append({
            "id": sku.id,
            "name": sku.name,
            "price": sku.price,
            "count": buy_num,
            "default_image_url": str(sku.default_image_url),
            "sku_sale_attr_name": sku_sale_attr_name,  # 销售属性名称列表
            "sku_sale_attr_val": sku_sale_attr_val,  # 销售属性值列表
            "selected": 1
        })
        return skus_list
        pass
    def get_redis_carts_list_data(self,user):
        key = self.get_cache_key(user)
        redis_carts_data = CARTS_CACHE.get(key)
        print(redis_carts_data, "获取购物车数据")
        skus_list = []
        if redis_carts_data:
            for sku_id, count in redis_carts_data.items():
                sku = SKU.objects.get(id=sku_id)

                sku_sale_attr_name = []
                sku_sale_attr_val = []
                sale_attr_values = sku.sale_attr_value.all()
                for sale_attr_value in sale_attr_values:
                    # 获取销售属性名称（从 SPUSaleAttr 获取）
                    sku_sale_attr_name.append(sale_attr_value.spu_sale_attr.name)  # 添加属性名称（如 "尺寸", "颜色"）
                    sku_sale_attr_val.append(sale_attr_value.name)  # 添加属性值（如 "18寸", "蓝色"）

                skus_list.append({
                    "id": sku.id,
                    "name": sku.name,
                    "price": sku.price,
                    "count": count[0],
                    "default_image_url": str(sku.default_image_url),
                    "sku_sale_attr_name": sku_sale_attr_name,  # 销售属性名称列表
                    "sku_sale_attr_val": sku_sale_attr_val,  # 销售属性值列表
                    "selected": count[1]
                })
            return skus_list

    def get_carts_dict(self, user):
        key = self.get_cache_key(user)
        redis_carts_data = CARTS_CACHE.get(key)
        print(redis_carts_data, "获取购物车数据")
        #{sku_id1:[count,1],sku_id2:[count,1]}
        # #字典在循环时不允许修改，所以先转为列表，再循环
        # for sku_id,count in list(redis_carts_data.items()):
        #     if count[1]==0:
        #         redis_carts_data.pop(sku_id)


        return {k:v for k,v in redis_carts_data.items() if v[1]==1}


        pass

    def del_cart_dict(self, user):
        key = self.get_cache_key(user)
        redis_carts_data = CARTS_CACHE.get(key)
        print(redis_carts_data, "获取购物车数据")
        # 第一步：找出要删除的键
        keys_to_delete = {k for k, v in redis_carts_data.items() if v[1] == 1}

        # 第二步：在循环外删除
        for k in keys_to_delete:
            redis_carts_data.pop(k, None)  # 安全删除

        # 第三步：保存回 Redis
        CARTS_CACHE.set(key, redis_carts_data)

        return redis_carts_data



